package com.atguigu.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.common.exception.NoStockException;
import com.atguigu.gulimall.common.to.OrderTo;
import com.atguigu.gulimall.common.utils.PageUtils;
import com.atguigu.gulimall.common.utils.Query;
import com.atguigu.gulimall.common.utils.R;
import com.atguigu.gulimall.common.vo.MemberRespVo;
import com.atguigu.gulimall.order.constant.OrderConstant;
import com.atguigu.gulimall.order.dao.OrderDao;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.gulimall.order.entity.PaymentInfoEntity;
import com.atguigu.gulimall.order.enume.OrderStatusEnum;
import com.atguigu.gulimall.order.feign.CartFeignService;
import com.atguigu.gulimall.order.feign.MemberFeignService;
import com.atguigu.gulimall.order.feign.ProductFeignService;
import com.atguigu.gulimall.order.feign.WmsFeignService;
import com.atguigu.gulimall.order.interceptor.LoginUserInterceptor;
import com.atguigu.gulimall.order.service.OrderItemService;
import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.service.PaymentInfoService;
import com.atguigu.gulimall.order.to.OrderCreateTo;
import com.atguigu.gulimall.order.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private ThreadLocal<OrderSubmitVo> confirmVoThreadLocal = new ThreadLocal<>();

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private MemberFeignService memberFeignService;

    @Autowired
    private CartFeignService cartFeignService;

    @Autowired
    private WmsFeignService wmsFeignService;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    ThreadPoolExecutor executor;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    private PaymentInfoService paymentInfoService;

    @Transactional
    @Override
    public String handlePayResult(PayAsyncVo payAsyncVo) {

        // 保存交易流水
        PaymentInfoEntity paymentInfoEntity = new PaymentInfoEntity();
        paymentInfoEntity.setOrderSn(payAsyncVo.getOut_trade_no());
        paymentInfoEntity.setAlipayTradeNo(payAsyncVo.getTrade_no());
        paymentInfoEntity.setCallbackTime(payAsyncVo.getNotify_time());
        paymentInfoEntity.setPaymentStatus(payAsyncVo.getTrade_status());
        paymentInfoService.save(paymentInfoEntity);

        // 修改订单状态信息
        if ("TRADE_SUCCESS".equals(payAsyncVo.getTrade_status())){
            // 支付成功状态
            String out_trade_no = payAsyncVo.getOut_trade_no();
            this.baseMapper.updateOrderStatus(out_trade_no, OrderStatusEnum.PAYED.getCode());
        }
        return "success";
    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id",memberRespVo.getId()).orderByDesc("id")
        );
        List<OrderEntity> order_sn = page.getRecords().stream().map(order -> {
            QueryWrapper<OrderItemEntity> queryWrapper = new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn());
            List<OrderItemEntity> list = orderItemService.list(queryWrapper);
            order.setItemEntities(list);
            return order;
        }).collect(Collectors.toList());
        page.setRecords(order_sn);

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PayVo getOrderPay(String orderSn) {

        PayVo payVo = new PayVo();
        OrderEntity order = this.getOrderByOrderSn(orderSn);

        BigDecimal bigDecimal = order.getPayAmount().setScale(2, BigDecimal.ROUND_UP);
        payVo.setTotal_amount(bigDecimal.toString());
        payVo.setOut_trade_no(orderSn);

        List<OrderItemEntity> list = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order));
        if (list != null && list.size() > 0){
            OrderItemEntity orderItem = list.get(0);
            payVo.setSubject(orderItem.getSkuName());
            payVo.setBody(orderItem.getSkuAttrsVals());
        }
        return payVo;
    }

    @Override
    public void closeOrder(OrderEntity order) {
        // 查询这个订单的最新状态
        OrderEntity entity = this.getById(order.getId());
        if (OrderStatusEnum.CREATE_NEW.getCode().equals(entity.getStatus())){
            // 关单
            OrderEntity update = new OrderEntity();
            update.setId(entity.getId());
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(update);
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(entity, orderTo);
            rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other", orderTo);
        }
    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        return this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
    }

    @Override
    public OrderConfirmVo confirmOrder() {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        OrderConfirmVo confirmVo = new OrderConfirmVo();
        System.out.println("主线程..." + Thread.currentThread().getId());
        // 获取之前的请求
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        CompletableFuture<Void> addressFuture = CompletableFuture.runAsync(() -> {
            System.out.println("member线程..." + Thread.currentThread().getId());
            // 放到子线程
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<MemberAddressVo> addresses = memberFeignService.getAddresses(memberRespVo.getId());
            confirmVo.setAddress(addresses);
        }, executor);

        CompletableFuture<Void> itemsFuture = CompletableFuture.runAsync(() -> {
            System.out.println("cart线程..." + Thread.currentThread().getId());
            // 放到子线程
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVo> items = cartFeignService.getCurrentUserCartItems();
            confirmVo.setItems(items);
        }, executor).thenRunAsync(()->{
            List<OrderItemVo> items = confirmVo.getItems();
            List<Long> skuIdList = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            R hasStock = wmsFeignService.getSkuHasStock(skuIdList);
            List<SkuStockVo> data = hasStock.get("data", new TypeReference<List<SkuStockVo>>() {
            });
            Map<Long, Boolean> map = data.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
            confirmVo.setStocks(map);
        }, executor);

        Integer integration = memberRespVo.getIntegration();
        confirmVo.setIntegration(integration);

        // 其他数据自行计算
        // TODO 5. 防重令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX+memberRespVo.getId(), token, 30, TimeUnit.MINUTES);
        confirmVo.setOrderToken(token);


        try {
            CompletableFuture.allOf(addressFuture, itemsFuture).get();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return confirmVo;
    }


    @Transactional
    public void a(){
        OrderServiceImpl service = (OrderServiceImpl) AopContext.currentProxy();
        service.b();
        service.c();
    }
    @Transactional(propagation = Propagation.REQUIRED)
    public void b(){

    }
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void c(){

    }


//    @GlobalTransactional
    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        // 下单，创建订单，验令牌，验价格， 锁库存
        SubmitOrderResponseVo  response = new SubmitOrderResponseVo();
        confirmVoThreadLocal.set(vo);
        response.setCode(0);
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        // 1. 验证令牌， 令牌的获取比对和删除必须是原子的
        // 0 令牌失败   1 删除成功
        String script = "if redis.call('get', KEYS[1]) ==ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        String orderToken = vo.getOrderToken();
        Long result = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId()), orderToken);
        if (result == 0){
            // 验证令牌失败
            response.setCode(1);
            return response;
        }else {
            // 验证令牌成功
            // 1. 创建订单
            OrderCreateTo orderTo = createOrder();
            // 2. 验价
            BigDecimal payAmount = orderTo.getOrder().getPayAmount();
            BigDecimal payPrice = vo.getPayPrice();
            // 金额对比
            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01){
                // TODO 3. 保存订单
                saveOrderTo(orderTo);
                // 锁库存， 只要有异常回滚订单数据
                // 订单号，所有的订单项（skuId， skuName， num）
                WareSkuLockVo lockVo = new WareSkuLockVo();
                lockVo.setOrderSn(orderTo.getOrder().getOrderSn());
                List<OrderItemVo> locks = orderTo.getOrderItems().stream().map(item -> {
                    OrderItemVo itemVo = new OrderItemVo();
                    itemVo.setSkuId(item.getSkuId());
                    itemVo.setCount(item.getSkuQuantity());
                    itemVo.setTitle(item.getSkuName());
                    return itemVo;
                }).collect(Collectors.toList());
                lockVo.setLocks(locks);
                // TODO 4. 远程锁库存
                R r = wmsFeignService.orderLockStock(lockVo);
                if (r.getCode() == 0){
                    // 锁成功
                    response.setOrder(orderTo.getOrder());
                    // TODO 5. 用户扣积分异常
//                    int i = 10 / 0;
                    // TODO 6. 订单信息发送到mq
                    rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", orderTo.getOrder());
                    return response;
                }else {
                    // 锁定失败
                    throw new NoStockException(r.getMsg());
//                    response.setCode(3);
//                    return response;
                }
            }else {
                response.setCode(2);
                return response;
            }
        }
    }

    /**
     * 保存订单数据
     * @param orderTo
     */
    private void saveOrderTo(OrderCreateTo orderTo) {
        OrderEntity order = orderTo.getOrder();
        order.setModifyTime(new Date());
        this.save(order);

        List<OrderItemEntity> orderItems = orderTo.getOrderItems();
        if (orderItems != null && orderItems.size() > 0){
//        orderItemService.saveBatch(orderItems);
            for (OrderItemEntity orderItem : orderItems) {
                orderItemService.save(orderItem);
            }
        }

    }

    /**
     * 创建订单实体类
     * @return
     */
    private OrderCreateTo createOrder() {
        OrderCreateTo createTo = new OrderCreateTo();
        // 1. 生成订单号  雪花算法
        String orderSn = IdWorker.getTimeId();
        // 获取订单信息
        OrderEntity order = buildOrder(orderSn);
        // 2. 获取所有订单项
        List<OrderItemEntity> orderItemList = buildOrderItemList(orderSn);
        // 3. 验价，计算价格相关
        computePrice(order, orderItemList);

        createTo.setOrder(order);
        createTo.setOrderItems(orderItemList);
        return createTo;
    }

    private void computePrice(OrderEntity order, List<OrderItemEntity> orderItemList) {
        BigDecimal total = new BigDecimal("0.0");
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");
        BigDecimal gift = new BigDecimal("0.0");
        BigDecimal growth = new BigDecimal("0.0");
        for (OrderItemEntity orderItem : orderItemList) {
            total = total.add(orderItem.getRealAmount());
            coupon = coupon.add(orderItem.getCouponAmount());
            integration = integration.add(orderItem.getIntegrationAmount());
            promotion = promotion.add(orderItem.getPromotionAmount());

            gift = gift.add(new BigDecimal(orderItem.getGiftIntegration().toString()));
            growth = growth.add(new BigDecimal(orderItem.getGiftGrowth().toString()));
        }
        // 价格信息
        order.setTotalAmount(total);        // 订单总额
        order.setPayAmount(total.add(order.getFreightAmount())); // 应付总额=订单总额+运费
        order.setCouponAmount(coupon);
        order.setIntegrationAmount(coupon);
        order.setPromotionAmount(coupon);
        // 积分信息
        order.setIntegration(gift.intValue());
        order.setGrowth(growth.intValue());
        // 状态信息
        order.setDeleteStatus(0); // 未删除
    }

    /**
     * 获取所有订单项信息
     * @return
     */
    private List<OrderItemEntity> buildOrderItemList(String orderSn) {
        List<OrderItemVo> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
        if (currentUserCartItems != null && currentUserCartItems.size() > 0){
            List<OrderItemEntity> collect = currentUserCartItems.stream().map(cartItem -> {
                OrderItemEntity orderItem = buildOrderItem(cartItem);
                orderItem.setOrderSn(orderSn);
                return orderItem;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    /**
     * 获取所有订单项信息
     * @return
     */
    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
        OrderItemEntity orderItem = new OrderItemEntity();
        // 1. 订单信息： 订单号，有了 orderSn
        // 2. 商品SPU信息
        Long skuId = cartItem.getSkuId();
        R r = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo data = r.getData(new TypeReference<SpuInfoVo>() {
        });
        orderItem.setSpuId(data.getId());
        orderItem.setSpuBrand(data.getBrandId().toString());
        orderItem.setSpuName(data.getSpuName());
        orderItem.setCategoryId(data.getCatalogId());

        // 3. 商品sku信息
        orderItem.setSkuId(cartItem.getSkuId());
        orderItem.setSkuName(cartItem.getTitle());
        orderItem.setSkuPic(cartItem.getImage());
        orderItem.setSkuPrice(cartItem.getPrice());
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        orderItem.setSkuAttrsVals(skuAttr);
        orderItem.setSkuQuantity(cartItem.getCount());
        // 4. 优惠信息（不做）
        // 5. 积分信息
        orderItem.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        orderItem.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        // 6. 订单项的价格信息
        orderItem.setPromotionAmount(new BigDecimal("0"));  // 商品促销分解金额
        orderItem.setCouponAmount(new BigDecimal("0")); // 优惠券优惠分解金额
        orderItem.setIntegrationAmount(new BigDecimal("0")); // 优惠券优惠分解金额
        // 当前订单项的实际金额
        orderItem.setRealAmount(orderItem.getSkuPrice()
                .multiply(new BigDecimal(orderItem.getSkuQuantity().toString()))
                .subtract(new BigDecimal(orderItem.getCouponAmount().toString()))
                .subtract(new BigDecimal(orderItem.getPromotionAmount().toString()))
                .subtract(new BigDecimal(orderItem.getIntegrationAmount().toString())));



        return orderItem;
    }

    /**
     * 获取订单信息
     * @return
     */
    private OrderEntity buildOrder(String orderSn) {
        OrderSubmitVo submitVo = confirmVoThreadLocal.get();
        // 创建订单
        OrderEntity order = new OrderEntity();
        order.setOrderSn(orderSn);
        order.setStatus(OrderStatusEnum.CREATE_NEW.getCode());

        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        order.setMemberId(memberRespVo.getId());

        // 获取地址运费信息
        R r = wmsFeignService.getFare(submitVo.getAddrId());
        FareVo data = r.getData(new TypeReference<FareVo>() {
        });
        // 设置运费
        order.setFreightAmount(data.getFare());

        // 设置收货人信息
        order.setReceiverCity(data.getAddress().getCity());
        order.setReceiverDetailAddress(data.getAddress().getDetailAddress());
        order.setReceiverName(data.getAddress().getName());
        order.setReceiverPhone(data.getAddress().getPhone());
        order.setReceiverPostCode(data.getAddress().getPostCode());
        order.setReceiverProvince(data.getAddress().getProvince());
        order.setReceiverRegion(data.getAddress().getRegion());

        return order;
    }
}